<template>
  <div class="requirement-management-detail">
    <!-- 上方展示信息区域 -->
    <div class="header-info">
      <div class="info-left">
        <!-- 需求名称区域 -->
        <div class="requirement-name-container">
          <span class="requirement-name-title">需求名称：</span>
          <span class="requirement-name-value">
            {{ requirementData.dname || '某公司的新增需求' }}
            <el-icon @click="handleNameIconClick" class="edit-icon">
              <EditPen />
            </el-icon>
          </span>
        </div>
        <!-- 添加缺少的两个字段，放在需求名称下方 -->
        <div class="additional-info">
          <span class="requirement-type">需求类别：{{ requirementData.dtype === 1 ? '工程类' : requirementData.dtype === 2 ? '直销类' : '未设置' }}</span>
          <span class="material-content">物料内容：{{ requirementData.materialName || '未设置' }}</span>
        </div>
      </div>
      <div class="info-right">
        <el-button @click="handleCancel" plain>取消</el-button>
        <el-button @click="handleSave('1')" type="primary" plain>保存</el-button>
        <el-button @click="handleSave('2')" type="primary" :disabled="isConfirmButtonDisabled">确认</el-button>
      </div>
    </div>

    <!-- 下方左右布局区域 - 添加边框 -->
    <div class="main-content-container">
      <!-- 左侧选项卡 -->
      <div class="left-sidebar">
        <h3 class="config-title">配置内容</h3>
        <div class="tab-container">
          <div
            class="tab-item"
            :class="{ active: activeTab === 'technical' }"
            @click="switchToTab('technical')"
          >
            <span class="dot"></span>
            <span class="tab-text">技术参数配置</span>
          </div>
          <div
            class="tab-item"
            :class="{ active: activeTab === 'business' }"
            @click="switchToTab('business')"
          >
            <span class="dot"></span>
            <span class="tab-text">业务参数配置</span>
          </div>
        </div>
      </div>

      <!-- 中间分割线 -->
      <div class="divider"></div>

      <!-- 右侧内容区域 -->
      <div class="right-content">
        <!-- 右侧标题 -->
        <div class="right-header">
          <h3 class="content-title">
            {{ activeTab === 'technical' ? '技术参数配置' : '业务参数配置' }}
          </h3>
        </div>

        <!-- 右侧内容 -->
        <div class="content-area">
          <!-- 技术参数配置内容区（留白） -->
          <div v-if="activeTab === 'technical'" class="technical-content">
            <Luckysheet
              :url="requirementData.file"
              :editable="true"
              :height="420"
              @save="handleTechnicalParamSave"
            >
              <template #toolbar-extra>
                <el-button @click="handleImport" type="primary" plain> 导入Excel </el-button>
              </template>
            </Luckysheet>
          </div>

          <!-- 业务参数配置内容区（表单） -->
          <div v-else-if="activeTab === 'business'" class="business-content">
            <el-form
              ref="businessFormRef"
              :model="businessForm"
              :rules="businessFormRules"
              class="business-form"
            >
              <el-form-item label="紧急程度：" prop="degreeUrgency">
                <el-select
                  v-model="businessForm.degreeUrgency"
                  placeholder="请选择紧急程度"
                  style="width: 200px"
                >
                  <el-option
                    v-for="option in urgencyLevelOptions"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                  ></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="交付日期：" prop="delivery">
                <el-date-picker
                  v-model="businessForm.delivery"
                  type="datetime"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  placeholder="选择日期"
                  :disabled-date="(time) => {
                    // 禁用今天及之前的日期，只允许选择明天及以后的日期
                    const today = new Date();
                    today.setHours(0, 0, 0, 0,);
                    return time <= today;
                  }"
                  style="width: 200px"
                />
              </el-form-item>

              <el-form-item label="客户要求：" prop="requirements">
                <el-input
                  v-model="businessForm.requirements"
                  type="textarea"
                  placeholder="支持1~256位字符"
                  :rows="4"
                  style="width: 400px"
                />
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加弹窗组件 -->
    <create-modal
      v-model:visible="showCreateModal"
      :requirement-type-options="requirementTypeOptions"
      :material-tree-data="materialTreeData"
      :initial-form-data="editFormData"
      :edit-mode="true"
      @submit="handleModalSubmit"
    />

    <!-- 隐藏的文件选择器 -->
    <input
      ref="fileInputRef"
      type="file"
      accept=".xlsx,.xls"
      style="display: none"
      @change="handleFileChange"
    />
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { EditPen } from '@element-plus/icons-vue'
// 导入弹窗组件
import CreateModal from './createModal.vue'
import Luckysheet from '@/components/Luckysheet/index.vue'
import {
  getDemandDetail,
  editorDemandBa, //编辑基本信息
  uploadData,
  editorDemand
} from '@/api/business/demand'
import {
  getClassificationTree,
  getMaterialPage,
} from '@/api/system/materials'
const router = useRouter()
const route = useRoute()
// 活动选项卡
const activeTab = ref('technical')

// 需求数据
const requirementData = reactive({
  file: '',
  dname: '',
  dtype: '',
  materialName: '',
  degreeUrgency: '',
  delivery: '',
  requirements: '',
  mid: ''
})
// 基本信息表单数据(编辑)
const editFormData = reactive({})

// 紧急程度选项数组
const urgencyLevelOptions = ref([
  { label: '一般', value: 1 },
  { label: '正常', value: 2 },
  { label: '紧急', value: 3 }
])

// 业务参数表单数据
const businessForm = reactive({
  degreeUrgency: undefined, // 默认一般（对应value为1）
  delivery: '', // 默认日期
  requirements: ''
})

// 业务参数表单验证规则
const businessFormRules = {
  degreeUrgency: [{ required: true, message: '请选择紧急程度', trigger: 'change' }],
  delivery: [{ required: true, message: '请选择交付日期', trigger: 'change' }],
  requirements: [
    { required: true, message: '请输入客户要求', trigger: 'blur' },
    { min: 1, max: 256, message: '客户要求长度在1到256个字符之间', trigger: 'blur' }
  ]
}

// 业务参数表单引用
const businessFormRef = ref()

// 文件选择器引用
const fileInputRef = ref()
// 控制弹窗显示
const showCreateModal = ref(false)

// 需求类型选项（根据实际情况获取）
const requirementTypeOptions = ref([
  { label: '工程类', value: 1 },
  { label: '直销类', value: 2 }
])
// 保存原始分类数据
let classificationTreeData = []
// 物料树数据（根据实际情况获取）
const materialTreeData = ref([])

// 保存初始数据的状态，用于检测是否有改动
const initialData = reactive({
  businessForm: {},
  requirementDataFile: ''
})

// 标记是否有未保存的改动
const hasUnsavedChanges = ref(false)

// 确认按钮是否禁用（状态为2时需要校验）
const isConfirmButtonDisabled = computed(() => {
  // 检查业务表单是否填写完整
  const isBusinessFormComplete = businessForm.degreeUrgency && 
                                 businessForm.delivery && 
                                 businessForm.requirements
  // 检查技术参数文件是否上传
  const isFileUploaded = requirementData.file !== ''
  
  // 当两个条件都满足时，确认按钮才可点击
  return !(isBusinessFormComplete && isFileUploaded)
})

// 监听数据变化，检测是否有未保存的改动
watch(
  () => [businessForm, requirementData.file],
  () => {
    // 简单比较，实际项目中可能需要更复杂的比较逻辑
    const hasBusinessFormChanges = JSON.stringify(businessForm) !== JSON.stringify(initialData.businessForm)
    const hasFileChanges = requirementData.file !== initialData.requirementDataFile
    
    hasUnsavedChanges.value = hasBusinessFormChanges || hasFileChanges
  },
  { deep: true }
)
// 处理需求名称图标点击
const handleNameIconClick = () => {
  // 填充编辑表单数据
  Object.assign(editFormData, requirementData)
  showCreateModal.value = true
}
// 切换配置项
const switchToTab = (tabName) => {
  // 当切换到业务参数配置时，需要校验技术参数文件是否已上传
  if (tabName === 'business' && !requirementData.file) {
    ElMessage.warning('请先完成技术参数配置')
    return
  }
  // 如果校验通过或切换到技术参数配置，则直接切换
  activeTab.value = tabName
}
// 监听路由参数变化，更新流程信息
watch(
  () => route.params,
  (newParams) => {
    if (newParams.requirementId || newParams.id) {
      const requirementId = newParams.requirementId || newParams.id
      getDemandDetail(requirementId).then(res => {
        if (res.code === 200 && res.data) {
          // console.log('res.data', res.data)
          // 使用对象接收返回的数据并赋值
          requirementData.dname = res.data.dname || '-'
          requirementData.dtype = res.data.dtype || ''
          requirementData.materialName = res.data.materialName || '-'
          requirementData.file = res.data?.file || '',
          requirementData.mid = res.data?.mid || '',
          Object.assign(editFormData, res?.data)
          Object.assign(businessForm, JSON.parse(res?.data?.businessParam || '{}') || {})
          
          // 保存初始数据，用于检测是否有改动
          Object.assign(initialData.businessForm, businessForm)
          initialData.requirementDataFile = requirementData.file
          hasUnsavedChanges.value = false
        }
      }).catch(() => {})
    }
  },
  { immediate: true, deep: true }
)
// 处理取消按钮点击
const handleCancel = () => {
  // 如果有未保存的改动，显示确认对话框
  if (hasUnsavedChanges.value) {
    ElMessageBox.confirm('存在未保存内容，确认取消？', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      router.push({
        path: '/business/demand'
      })
    }).catch(() => {
      // 用户点击取消，不执行任何操作
    })
  } else {
    // 没有改动，直接返回
    router.push({
      path: '/business/demand'
    })
  }
}
// 物料内容
const fetchCategories = () => {
  getClassificationTree().then((res) => {
    if (res.data && Array.isArray(res.data)) {
      // 保存原始分类数据
      classificationTreeData = res.data
      // 初始化物料树数据结构
      updateMaterialTreeData([])
    } else {
      materialTreeData.value = []
      classificationTreeData = []
    }
  })
}
// 根据分类数据和物料数据更新物料树
const updateMaterialTreeData = (materials) => {
  if (!Array.isArray(classificationTreeData)) {
    materialTreeData.value = []
    return
  }
  
  // 转换数据格式，构造三级物料树
  materialTreeData.value = classificationTreeData.map(item => {
    // 一级分类节点
    const firstLevel = {
      label: item.name,
      value: item.id,
      disabled: true, // 一级分类不可选择
      children: []
    }
    
    // 处理二级分类节点
    if (item.children && item.children.length > 0) {
      firstLevel.children = item.children.map(child => {
        // 二级分类节点
        const secondLevel = {
          label: child.name,
          value: child.id,
          disabled: true, // 二级分类不可选择
          children: []
        }
        
        // 查找匹配当前二级分类的物料数据
        const matchedMaterials = materials.filter(material => 
          material.classification === child.id
        )
        
        // 添加三级物料节点
        if (matchedMaterials.length > 0) {
          secondLevel.children = matchedMaterials.map(material => ({
            label: material.materialName,
            value: material.id,
            disabled: false // 三级物料可选择
          }))
        }
        
        return secondLevel
      })
    }
    
    // 查找直接匹配一级分类的物料数据（如果有）
    const firstLevelMaterials = materials.filter(material => 
      material.classification === item.id
    )
    
    // 如果有直接匹配一级分类的物料，添加到每个二级分类下
    if (firstLevelMaterials.length > 0) {
      firstLevel.children.forEach(secondLevel => {
        firstLevelMaterials.forEach(material => {
          secondLevel.children.push({
            label: material.materialName,
            value: material.id,
            disabled: false
          })
        })
      })
    }
    
    return firstLevel
  })
}

// 查询物料分类下具体内容
const fetchMaterialDetails = () => {
  getMaterialPage({ pageNum: 1, pageSize: 10000,}).then(res => {
    if (res.code === 200 && res.data && res.data.list) {
      // 更新物料树数据
      updateMaterialTreeData(res.data.list)
    }
  })
}
// 初始化
onMounted(() => {
  fetchCategories()
  fetchMaterialDetails()
})

// 处理保存按钮点击
const handleSave = async (type) => {
  // 对于状态为2（确认）的情况，额外检查是否都已配置完成
  if (type === '2' && isConfirmButtonDisabled.value) {
    ElMessage.warning('请先完成所有配置项')
    return
  }
  
  const object = {
    deId: Number(editFormData?.id),
    businessEntity: {
      ...businessForm
    },
    uploadData: requirementData.file,
    status: Number(type)
  }
  try {
    if(type === '2'){
      await businessFormRef.value.validate()
    }
    editorDemand(object).then(res => {
      if (res.code === 200) {
        ElMessage.success(`${type === 1 ? '保存' : '确认'}保存成功`)
        // 保存成功后，更新初始数据状态，重置未保存标记
        Object.assign(initialData.businessForm, businessForm)
        initialData.requirementDataFile = requirementData.file
        hasUnsavedChanges.value = false
      }
    }).catch(() => {})
  } catch (error) {
    // 表单验证失败，显示警告信息
    ElMessage.warning('请完善业务参数')
  }
}

// 处理导入按钮点击
const handleImport = () => {
  // 触发文件选择
  if (fileInputRef.value) {
    fileInputRef.value.click()
  }
}

// 处理文件选择变化
const handleFileChange = async (event) => {
  const file = event.target.files?.[0]
  if (!file) {
    return
  }
  // 验证文件类型
  const fileExtension = file.name.split('.').pop()?.toLowerCase()
  if (!['xlsx', 'xls'].includes(fileExtension)) {
    ElMessage.error('请选择Excel文件（.xlsx 或 .xls）')
    // 清空文件选择器
    if (fileInputRef.value) {
      fileInputRef.value.value = ''
    }
    return
  }

  try {
    // 创建FormData
    const formData = new FormData()
    formData.append('file', file)
    formData.append('id', Number(requirementData.mid))
    // 调用上传接口
    uploadData(formData).then(res => {
      // console.log('上传之后返回的数据:', res);
      if (res.code === 200) {
        // 上传成功，更新文件URL
        requirementData.file = res.data || ''
        ElMessage.success('上传成功')
      }
    }).catch(error => {})
  } catch (error) {
    ElMessage.error('文件上传失败: ' + (error.message || '未知错误'))
  } finally {
    // 清空文件选择器，以便可以重复选择同一文件
    if (fileInputRef.value) {
      fileInputRef.value.value = ''
    }
  }
}

// 处理技术参数保存
const handleTechnicalParamSave = async (data) => {
  try {
    if (!data.file) {
      ElMessage.error('文件数据为空')
      return
    }
    const formData = new FormData()
    formData.append('file', data.file, data.fileName || 'technical_param.xlsx')
    formData.append('id', Number(requirementData.mid))
    // 调用上传接口
    uploadData(formData).then(res => {
      // console.log('编辑之后返回的数据:', res);
      if (res.code === 200) {
        // 上传成功，更新文件URL
        requirementData.file = res.data || ''
        ElMessage.success('技术参数保存成功')
      }
    }).catch(error => {})
  } catch (error) {
    ElMessage.error('保存失败: ' + (error.message || '未知错误'))
  }
}

// 处理弹窗提交
const handleModalSubmit = (formData) => {
  // 处理提交逻辑
  const params = {
    ...formData,
    deId: Number(editFormData?.id),
    deName: formData.deName, //需求名称
    deType: Number(formData.deType), //需求类别；1工程类、2直销类
    maId: Number(formData.maId) //物料Id
  }
  editorDemandBa(params).then(res => {
    if (res.code === 200) {
      ElMessage.success('编辑成功')
      // 关闭弹窗
      emit('close')
      // 刷新当前需求详情
      getDemandDetail(editFormData?.id).then(res => {
        if (res.code === 200 && res.data) {
          // 使用对象接收返回的数据并赋值
          requirementData.dname = res.data.dname || '-'
          requirementData.dtype = res.data.dtype || ''
          requirementData.materialName = res.data.materialName || '-'
          requirementData.file = res.data.file || ''
          Object.assign(editFormData, res.data)
          router.push({ path: `/system/materials-detail/edit/${Number(formData.maId)}` })
        }
      }).catch(() => {})
    } else {
      ElMessage.error(res.msg || '编辑失败')
    }
  })
}
</script>

<style lang="scss" scoped>
@import '@/assets/styles/createRequirement.scss';
</style>
